package com.acceptable.qucun.file.aspect;

import com.acceptable.qucun.file.entity.template.TemplateFile;
import com.acceptable.qucun.file.exception.FileOperationException;
import com.acceptable.qucun.file.mapper.TemplateFileMapper;
import com.acceptable.qucun.generic.util.AspectUtil;
import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.StringFormatUtil;
import com.acceptable.qucun.generic.util.result.error.FileErrorResult;
import com.acceptable.qucun.generic.util.verify.FormatVerifyUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Aspect
@Component
public class FileDatabaseAspect {
    @Autowired private TemplateFileMapper fileMapper;

    @Pointcut("execution(* com.acceptable.qucun.file.service.TemplateFileService.*ExistedSingle*(..))")
    public void single(){}

    @Pointcut("execution(* com.acceptable.qucun.file.service.TemplateFileService.*ExistedMulti*(..))")
    public void multi(){}

    @Before(value = "single()")
    public void singleFileExist(JoinPoint joinPoint){
        Map<String, Object> paramMap = AspectUtil.paramMap(joinPoint);
        Integer userId = (Integer) paramMap.get("Integer");
        Long fileId = (Long) paramMap.get("Long");
        Map<String, String> dataMap = (Map<String, String>) paramMap.get("HashMap");

        if (userId == null && !FormatVerifyUtil.mapIsEmpty(dataMap)){
            userId = Integer.parseInt(dataMap.get("user_id"));
        }

        if (fileId == null && !FormatVerifyUtil.mapIsEmpty(dataMap)){
            fileId = Long.parseLong(dataMap.get("file_id"));
        }

        if (fileId == null || userId == null)
            return;
        TemplateFile file = fileMapper.selectByFileId(userId, fileId);
        if (file == null)
            throw new FileOperationException(FileErrorResult.NOT_EXIST_ERROR);
    }

    @Before(value = "multi()")
    public void multiFileExist(JoinPoint joinPoint){
        Map<String, Object> paramMap = AspectUtil.paramMap(joinPoint);
        Map<String, String> dataMap = (Map<String, String>) paramMap.get("HashMap");
        String userIdStr = dataMap.get("user_id");
        if(StringFormatUtil.isEmpty(userIdStr))
            userIdStr = dataMap.get("src_user_id");
        Integer userId = Integer.valueOf(userIdStr);
        List<Long> fileId = CodeUtil.string2List(dataMap.get("file_id"), Long.class);
        for (Long id: fileId){
            TemplateFile file = fileMapper.selectUndeletedById(userId, id);
            if (file == null){
                throw new FileOperationException(FileErrorResult.NOT_EXIST_ERROR);
            }
        }
    }

}
